//
//  RangeNotSupportViewController.m
//  FD
//
//  Created by xiaofang wang on 2018/11/7.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
// 超出配送范围

#import "RangeNotSupportViewController.h"
#import "RangNotSupportView.h"
//model
#import "MyAddressModel.h"
//地图
#import <GoogleMaps/GoogleMaps.h>



@interface RangeNotSupportViewController ()<GMSMapViewDelegate>

@property (nonatomic, strong)RangNotSupportView *notSupportView;
@property (nonatomic, strong) GMSMapView *mapView;
/**画形状*/
//@property (nonatomic, strong) GMSPolygon *polygon;

@end

@implementation RangeNotSupportViewController
{
    GMSMapView *_mapView;
    BOOL _firstLocationUpdate;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    [self loadData];
    
    [self setupSubView];
}

- (void)setupSubView {
    
    self.view.backgroundColor = kMainLightGrayColor;
    self.navigationItem.title = @"超出配送范围";
    
    
    //显示地图
    [self setupMapView];
    [self.view addSubview:self.notSupportView];
    
    FDLog(@"经纬度:%@--%@",self.addressModel.longitude, self.addressModel.latitude);
}

//地图
- (void)setupMapView {
    //创建定位di8abn
    /***/
    GMSCameraPosition *position = [GMSCameraPosition cameraWithLatitude:51.90027 longitude:-8.55794 zoom:1];
    //创建地图
    _mapView = [GMSMapView mapWithFrame:CGRectZero camera:position];
    _mapView.delegate = self;
    _mapView.settings.compassButton = YES; //显示罗盘地址
    _mapView.settings.myLocationButton = YES; //显示定位
    
    //监听d位置变化
    [_mapView addObserver:self forKeyPath:@"myLocation" options:(NSKeyValueObservingOptionNew) context:NULL];
    
    
    // Ask for My Location data after the map has already been added to the UI.
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_mapView.myLocationEnabled = YES;
    });
    
    //    51.90027   -8.55794
//    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.8903393, -8.55794);
//    GMSCameraUpdate *up = [GMSCameraUpdate setTarget:coordinate zoom:10];
//    [_mapView moveCamera:up];
    
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.8903393, -8.55794);
    GMSCameraUpdate *up = [GMSCameraUpdate setTarget:coordinate zoom:10];
    [_mapView moveCamera:up];

    self.view = _mapView; //赋值给控制器的veiw
}

- (RangNotSupportView *)notSupportView {
    if (!_notSupportView) {
        CGFloat h = 220;
        CGFloat y = SCREEN_HEIGHT - FD_TabbarSafeBottomMargin - h;
        
        CGFloat w = SCREEN_WIDTH - 10*2;
        _notSupportView = [[RangNotSupportView alloc] initWithFrame:CGRectMake(10, y, w, h-5)];
        
        //超出配送范围，点击确定直接返回
        FDWeakSelf;
        _notSupportView.clickSureBtnBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _notSupportView;
}

- (void)loadData {
    
    [self requestIsInRange:self.addressModel];
    
    [self requestShopRangeList];
}


#pragma mark - 请求数据
/**判断否在配送范围之内*/
- (void)requestIsInRange:(MyAddressModel *)model {
    
    //// [lat: 37.785834, lng: -]"
    NSNumber *lng = model.longitude;
    NSNumber *lat = model.latitude;
    if (!lng || !lat) { //如果无值就显示固定的
        lng = @122.406417;
        lat = @37.785834;
    }

//    model.longitude
//    model.latitude
    [FDHttpAPi requestUserShopInRnageWithLongitude:lng  latitude:lat successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSDictionary *data = responseObjc[@"data"];
            NSNumber *inRange = data[@"inRange"];
            if ([inRange isEqualToNumber:@(0)]) {
                FDLog(@"不在配送范围内");
            }else if([inRange isEqualToNumber:@(1)]) {
                FDLog(@"超出配送范围");
            }else {
                FDLog(@"未知");
            }
            
        }
    } failBlock:^(NSError *error) {
        
    }];
}

/**请求超出配送范围坐标*/
- (void)requestShopRangeList {
    [FDHttpAPi requestUserShopRangListSuccessBlock:^(id responseObjc) {
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            //画线
            [self fddrawPolygonWithResponDic:responseObjc[@"data"]];
            
            //画圆
//            CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.90027, -8.55794);
//            [self fdDrawCircleWithCircleCenter:coordinate];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}




#pragma mark - GMSMapViewDelegate

- (void)mapView:(GMSMapView *)mapView didTapMyLocation:(CLLocationCoordinate2D)location {
    NSString *message = [NSString stringWithFormat:@"My Location Dot Tapped at: [lat: %f, lng: %f]",
                         location.latitude, location.longitude];
    UIAlertController *alertController =
    [UIAlertController alertControllerWithTitle:@"Location Tapped"
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction *action){
                                                     }];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

//???修改地图的大小
- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
    FDLog(@"111111:%s--%d",__FUNCTION__,__LINE__);
}

- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
    FDLog(@"222222:%s--%d",__FUNCTION__,__LINE__);
}


- (void)dealloc {
    [_mapView removeObserver:self
                  forKeyPath:@"myLocation"
                     context:NULL];
}

#pragma mark - KVO updates

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (!_firstLocationUpdate) {
        // If the first location update has not yet been received, then jump to that
        // location.
        _firstLocationUpdate = YES;
        CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
        _mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
                                                         zoom:11];
    }
}


#pragma mark - 画范围
- (void)fddrawPolygonWithResponDic:(NSDictionary *)res {
    
    //创建path

    for (NSDictionary *dic in res) {
        NSArray *positionListArr = dic[@"positionList"];
        
        [self drawRangeWithArr:positionListArr];
    }
}



//注意调用两次。
- (void)drawRangeWithArr:(NSArray *)arr {
    
    GMSMutablePath *path = [GMSMutablePath path];
    for (NSDictionary *coordinateDic in arr) {
        CLLocationCoordinate2D coordinate = [self coordincate2DFromDic:coordinateDic];
        [path addCoordinate:coordinate]; //添加坐标
    }
    
    //添加路径GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
    GMSPolygon *polygon = [GMSPolygon polygonWithPath:path];
    polygon.fillColor = rgba(78, 180, 111, 0.8); // #4eb46f
    polygon.strokeColor = rgba(78, 180, 111, 0.8); // #4eb46f
    polygon.strokeWidth = 2.0;
    polygon.map = _mapView;
}

- (CLLocationCoordinate2D)coordincate2DFromDic:(NSDictionary *)dic; {
 
    //经度
    CGFloat longitude = [dic[@"longitude"] doubleValue];
    
    //纬度
    CGFloat latitude = [dic[@"latitude"] doubleValue];
    
    //转换成坐标
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake(latitude, longitude);
    
    return coordinate2D;
}

/**画圆*/
- (void)fdDrawCircleWithCircleCenter:(CLLocationCoordinate2D)circleCenter {
    GMSCircle *circ = [GMSCircle circleWithPosition:circleCenter radius:500];
    circ.fillColor = [UIColor redColor];
    circ.strokeColor = [UIColor blackColor];
    circ.strokeWidth = 2.0;
    circ.map = _mapView;
}

@end
